package Presentacion;

import Clases.Asignardeduccion;
import Clases.Deduccion;
import Control.ControlDeduccion;
import de.javasoft.plaf.synthetica.SyntheticaLookAndFeel;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.NumberFormatter;

public class InsertarModificarDeduccion extends javax.swing.JFrame {

    ControlDeduccion controlD = ControlDeduccion.obtenerInstancia();
    private ImageIcon iconoError;
    NumberFormat numberFormat = (DecimalFormat) DecimalFormat.getNumberInstance();
    Deduccion deduccion = null;

    private InsertarModificarDeduccion() {
        initComponents();
        inicioTooltops();
    }
    private static InsertarModificarDeduccion instancia = null;

    public static InsertarModificarDeduccion obtenerInstancia() {
        if (instancia == null) {
            instancia = new InsertarModificarDeduccion();
        }
        return instancia;
    }

    private void ocultarLabels() {

        jlabelMonto.setVisible(false);
        jlabelAmbos.setVisible(false);
        labelporcentaje.setVisible(false);
        labelDescripcion.setVisible(false);
    }

    private void inicioTooltops() {
        iconoError = new ImageIcon(getClass().getResource("/Imagenes/warning.png"));

        jlabelMonto.setIcon(iconoError);
        jlabelMonto.setToolTipText("Debe escribir un valor monetario mayor a mil colones.");

        labelporcentaje.setIcon(iconoError);
        labelporcentaje.setToolTipText("Debe escribir un número mayor que cero, por ejemplo 3.5 ó 3,5");

        jlabelAmbos.setIcon(iconoError);
        jlabelAmbos.setToolTipText("Debe escoger si la decuccióm es permanente o seleccionar el periodo de vigencia");

        labelDescripcion.setIcon(iconoError);
        labelDescripcion.setToolTipText("Debe escribir una descripción");

        ocultarLabels();
    }

    public void init(Deduccion deduccion) {
        jTextField3.setText("");
        ocultarLabels();
        setTitle("Deducción");
        setLocationRelativeTo(null);
        UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
        SwingUtilities.updateComponentTreeUI(this);
        try {
            UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
            SyntheticaLookAndFeel.setWindowsDecorated(false);
            UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);

        } catch (Exception ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.NumberFormat();
        if (deduccion != null) {
            this.deduccion = deduccion;
            jLabel11.setText(String.valueOf(deduccion.getCodigo()));
            jTextField2.setText(deduccion.getNombre());
            if (deduccion.isPermanente()) {
                jCheckBox1.setSelected(true);
                this.jDateChooser1.setEnabled(false);
                this.jDateChooser2.setEnabled(false);
            } else {
                jCheckBox1.setSelected(false);
                this.jDateChooser1.setEnabled(true);
                this.jDateChooser2.setEnabled(true);
            }

            if (deduccion.getMonto() != 0.0) {
                this.jComboBox1.setSelectedIndex(0);
                jTextField3.setText(Double.toString(deduccion.getMonto()));
            } else {
                this.jComboBox1.setSelectedIndex(1);
                jTextField4.setText(Double.toString(deduccion.getPorcentaje()));
            }
            jDateChooser1.setDate(deduccion.getFechaInicio());
            jDateChooser2.setDate(deduccion.getFechaFin());
        } else {
            this.limpiar();
        }

        this.setVisible(true);
    }

    public void NumberFormat() {
        numberFormat.setMaximumIntegerDigits(7);
        numberFormat.setMinimumFractionDigits(0);
        numberFormat.setMinimumIntegerDigits(2);
        NumberFormatter nfr = new NumberFormatter(numberFormat);
        this.jTextField3.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(nfr));
    }

    public static boolean esNumero(String str) {
        for (char c : str.toCharArray()) {       
            if (!Character.isDigit(c)) {
                if(!(c=='.'||c==',')){
                return false;
                }
            }
        }
        return true;
    }

    private boolean validarDeduccion(String descripcion, boolean permanente, String monto, String porcentaje, Date fechaInicio, Date fechaFin) {
        boolean itsOk = true;

        if (descripcion.equals("")) {
            labelDescripcion.setVisible(true);
            itsOk = false;
        }
        if (permanente == false) {
            if (fechaInicio == null || fechaFin == null) {
                jlabelAmbos.setVisible(true);
                itsOk = false;
            }
        }
        if (jComboBox1.getSelectedItem().toString().equals("Porcentaje")) {
            if (porcentaje.equals("")) {
                labelporcentaje.setVisible(true);
                itsOk = false;
            } else {
                if (!esNumero(porcentaje)) {
                    labelporcentaje.setVisible(true);
                    itsOk = false;
                } else {
                    if (Double.valueOf(porcentaje) <= 0.0) {
                        labelporcentaje.setVisible(true);
                        itsOk = false;
                    }
                }

            }
        }

        return itsOk;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();
        jLabel9 = new javax.swing.JLabel();
        jDateChooser2 = new com.toedter.calendar.JDateChooser();
        jLabel1 = new javax.swing.JLabel();
        jlabelMonto = new javax.swing.JLabel();
        labelporcentaje = new javax.swing.JLabel();
        jlabelAmbos = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JFormattedTextField();
        jTextField4 = new javax.swing.JFormattedTextField();
        labelDescripcion = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(420, 390));
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Código:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Descripción:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel4.setText("Monto:");

        jCheckBox1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jCheckBox1.setText("Permanente");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel5.setText("Porcentaje:");

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel6.setText("Vigencia:");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel8.setText("Deducción");

        jButton3.setText("Crear");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel7.setText("Inicia:");

        jDateChooser1.setDateFormatString("dd-MM-yyyy");

        jLabel9.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel9.setText("Expira:");

        jDateChooser2.setDateFormatString("dd-MM-yyyy");

        jLabel1.setText("%");

        jlabelMonto.setText("x");
        jlabelMonto.setMaximumSize(new java.awt.Dimension(24, 24));
        jlabelMonto.setMinimumSize(new java.awt.Dimension(22, 22));
        jlabelMonto.setPreferredSize(new java.awt.Dimension(22, 22));

        labelporcentaje.setText("x");
        labelporcentaje.setMaximumSize(new java.awt.Dimension(24, 24));
        labelporcentaje.setMinimumSize(new java.awt.Dimension(22, 22));
        labelporcentaje.setPreferredSize(new java.awt.Dimension(22, 22));

        jlabelAmbos.setText("x");
        jlabelAmbos.setMaximumSize(new java.awt.Dimension(24, 24));
        jlabelAmbos.setMinimumSize(new java.awt.Dimension(22, 22));
        jlabelAmbos.setPreferredSize(new java.awt.Dimension(22, 22));

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Monto", "Porcentaje" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel10.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel10.setText("Elija: ");

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jTextField4.setEditable(false);
        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });

        labelDescripcion.setText("x");
        labelDescripcion.setMaximumSize(new java.awt.Dimension(24, 24));
        labelDescripcion.setMinimumSize(new java.awt.Dimension(22, 22));
        labelDescripcion.setPreferredSize(new java.awt.Dimension(22, 22));

        jLabel11.setText("__________");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(jButton2))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jCheckBox1)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel10)
                                    .addComponent(jLabel4))
                                .addGap(12, 12, 12)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jlabelMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addGap(18, 18, 18)
                                .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel9)
                                .addGap(18, 18, 18)
                                .addComponent(jDateChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jlabelAmbos, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel11)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(labelDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(75, 75, 75)
                                .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(labelporcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(146, 146, 146)
                .addComponent(jLabel8)
                .addContainerGap(163, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel11))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField2)
                    .addComponent(labelDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jlabelMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jLabel1)
                            .addComponent(labelporcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(jCheckBox1)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7)
                            .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addComponent(jDateChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlabelAmbos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.limpiar();
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

        String codigoDeduccion = jLabel11.getText();
        String descripcion = jTextField2.getText();
        boolean permanente = jCheckBox1.isSelected();
        String monto = jTextField3.getText();
        String porcentaje = jTextField4.getText();
        Date fechaInicio = jDateChooser1.getDate();
        Date fechaFin = jDateChooser2.getDate();
        int inserto = -1;
        int error = 0;
        boolean modifico = false;
        ocultarLabels();
        double monto1 = 0;
        try {
            ///// VALIDACIONES ////////////////
            boolean validar = validarDeduccion(descripcion, permanente, monto, porcentaje, fechaInicio, fechaFin);

            if (jComboBox1.getSelectedItem().toString().equals("Monto")) {
                if (!monto.equals("")) {
                    monto1 = jTextField3.getText().trim().isEmpty() ? 0 : numberFormat.parse(jTextField3.getText()).doubleValue();
                    if (monto1 < 1000) {
                        jlabelMonto.setVisible(true);
                        error = 1;
                    }
                } else {
                    jlabelMonto.setVisible(true);
                    error = 1;
                }
            }

            // FIN VALIDACIONES ////////////////////////
            if (error == 0 && validar) {
                Double porcen = porcentaje.isEmpty() ? 0 : Double.parseDouble(porcentaje);
                   double porcenDecimales=(double)Math.round(porcen * 100) / 100;

                if (codigoDeduccion.equals("")) { // si esta vacio es xq es una insercion y hay q generarlo y sino es una modificacion

                    Deduccion nuevaDeduccion = new Deduccion(null, descripcion, monto1, porcenDecimales, permanente, fechaInicio, fechaFin, true);

                    inserto = controlD.insertarDeduccion(nuevaDeduccion);

                    if (inserto == -1) {
                        JOptionPane.showMessageDialog(null, "No se pudo insertar la deducción", "Mensaje", JOptionPane.ERROR_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(null, "Deducción ingresada con éxito", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                        dispose();
                    }
                } else {                  
                    boolean exito = true;
                    Deduccion deduccionModificada = new Deduccion(null, descripcion, monto1, porcen, permanente, fechaInicio, fechaFin, true);
                    deduccion.setActivo(false);
                    inserto = controlD.insertarDeduccion(deduccionModificada);
                    ArrayList<Asignardeduccion> asignaciones = controlD.obtenerAsignacionesActualesPorDeduccion(deduccion.getCodigo());
                    for (int j = 0; j < asignaciones.size(); j++) {
                        asignaciones.get(j).setDeduccion(deduccionModificada);
                        if (!controlD.modificarAsignacion(asignaciones.get(j))) {
                            exito = false;
                        }
                    }
                    if (controlD.tieneAsignaciones(deduccion.getCodigo())) {
                        modifico = controlD.modificarDeduccion(deduccion);
                    } else {
                        modifico = controlD.eliminarDeduccion(deduccion);
                    }
                    if (modifico && inserto != -1 && exito) {
                        JOptionPane.showMessageDialog(null, "Deducción modificada con éxito", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                        dispose();
                        limpiar();
                    } else {
                        JOptionPane.showMessageDialog(null, "No se pudo modificar la deducción, o  "
                                + " los empleados que tienen la deducción no se pudieron actualizar con los nuevos cambios", "Mensaje", JOptionPane.ERROR_MESSAGE);

                    }
                }
                Deducciones d = Deducciones.obtenerInstancia();
                d.llenarTablaDeducciones();
                dispose();
            }
        } catch (ParseException ex) {
            Logger.getLogger(InsertarModificarDeduccion.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButton3ActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        if (this.jCheckBox1.isSelected()) {
            this.jDateChooser1.setEnabled(false);
            this.jDateChooser2.setEnabled(false);
            this.jDateChooser1.cleanup();
            this.jDateChooser2.cleanup();
        } else {
            this.jDateChooser1.setEnabled(true);
            this.jDateChooser2.setEnabled(true);
        }
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        String seleccionado = (String) jComboBox1.getSelectedItem();
        if (seleccionado.equals("Monto")) {
            jTextField3.setEditable(true);
            jTextField4.setEditable(false);
            jTextField4.setText("");
            jTextField4.setValue(null);
        } else {
            jTextField4.setEditable(true);
            jTextField3.setEditable(false);
            jTextField3.setText("");
            jTextField3.setValue(null);
        }
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField4ActionPerformed

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField3ActionPerformed
    public static boolean isNumber(String string) {
        if (string == null || string.isEmpty()) {
            return false;
        }
        int i = 0;
        if (string.charAt(0) == '-') {
            if (string.length() > 1) {
                i++;
            } else {
                return false;
            }
        }
        for (; i < string.length(); i++) {
            if (!Character.isDigit(string.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public void limpiar() {
        jLabel11.setText("");
        jTextField2.setText("");
        jTextField3.setText("");
        jTextField3.setValue(null);
        jTextField4.setText("");
        jTextField4.setValue(null);
        jDateChooser1.setDate(null);
        jDateChooser2.setDate(null);
        jCheckBox1.setSelected(false);
        this.jDateChooser1.setEnabled(true);
        this.jDateChooser2.setEnabled(true);
        this.jComboBox1.setSelectedIndex(0);
        this.deduccion = null;
        this.ocultarLabels();
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(InsertarModificarDeduccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(InsertarModificarDeduccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(InsertarModificarDeduccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(InsertarModificarDeduccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new InsertarModificarDeduccion().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JComboBox jComboBox1;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private com.toedter.calendar.JDateChooser jDateChooser2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JFormattedTextField jTextField3;
    private javax.swing.JFormattedTextField jTextField4;
    private javax.swing.JLabel jlabelAmbos;
    private javax.swing.JLabel jlabelMonto;
    private javax.swing.JLabel labelDescripcion;
    private javax.swing.JLabel labelporcentaje;
    // End of variables declaration//GEN-END:variables
}
